#include "dialogreportpreview.h"
#include "ui_dialogreportpreview.h"

#include <QFile>
#include <QDate>
#include <QtCore>
#include <QDate>
#include <QTextDocument>
#include <QPrinter>
#include <QMessageBox>
#include <QDesktopServices>

DialogReportPreview::DialogReportPreview(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogReportPreview)
{
    ui->setupUi(this);
    loadTemplates();
}

DialogReportPreview::~DialogReportPreview()
{
    delete ui;
}

void DialogReportPreview::setTotalTurnOver(double value)
{
    m_totalTurnOver=value;
}

void DialogReportPreview::setTurnOverPerDay(const cs8ReportDataList &value)
{
    m_turnOverPerDay=value;
}

void DialogReportPreview::setSharePercent(double value)
{
    m_sharePercent=value;
}

void DialogReportPreview::setShareAbsolute(double value)
{
    m_shareAbsolute=value;
}

void DialogReportPreview::setListDays(bool value)
{
    m_listDays=value;
}

void DialogReportPreview::addSeller(const QString & id, const QString &name, cs8Seller *seller)
{
    QString turnover;
    turnover="<table border=\"1\" cellspacing=\"5\" cellpadding=\"5\">";
    //turnover=+"<colgroup><col width=\"160\"/><col width=\"120\"/></colgroup>";
    turnover+="<tr>";
    if (m_listDays)
        turnover+="<th>Datum</th>";
    turnover+="<th>Anzahl</th>";
    turnover+="<th>Einzelpreis</th>";
    turnover+="<th>Gesamtpreis</th>";
    turnover+=trUtf8 ("<th>Anteil EB (%1% )</th>").arg(m_sharePercent);

    turnover+="</tr>";

    QList<QDateTime> list=seller->sales ().uniqueKeys ();
    //for (int i=0;i<list.count ();i++)
    foreach(QDateTime transaction,list)
    {
        QList<sale*> sales=seller->sales ().values (transaction);
        foreach(sale* newSale,sales) {
            if (m_listDays) {
                turnover+=trUtf8 ("<tr><td> %1 </td><td> %2 </td><td> %3€ </td><td> %4€ </td><td> %5€ </td></tr>")
                        .arg(transaction.toString ("dddd, dd.MM.yyyy hh:mm"))
                        .arg(newSale->quantity())
                        .arg(newSale->price (),10,'f',2,' ')
                        .arg(newSale->total (),10,'f',2,' ')
                        .arg(newSale->total ()*m_sharePercent/100,10,'f',2,' ');
            } else {
                turnover+=trUtf8 ("<tr><td> %1 </td><td> %2€ </td><td> %3€ </td><td> %4€ </td></tr>")
                        .arg(newSale->quantity())
                        .arg(newSale->price (),10,'f',2,' ')
                        .arg(newSale->total (),10,'f',2,' ')
                        .arg(newSale->total ()*m_sharePercent/100,10,'f',2,' ');
            }
        }
    }
    turnover+="</table>";

    QString data=m_templateSeller;
    m_sellers+=QString(data)
            .arg(name)
            .arg(id)
            .arg(trUtf8 ("%1€  Abzüglich Anteil EB (%2%): %3")
                 .arg(seller->totalSum (),10,'f',2)
                 .arg(m_sharePercent,10,'f',1)
                 .arg(seller->totalSum ()-seller->totalSum ()*m_sharePercent/100,10,'f',2))
            .arg(turnover);
}

void DialogReportPreview::createPreview()
{
    QTextDocument *document=new QTextDocument(this);
    QTextCursor cursor(document);
    QTextBlockFormat blockFormat;
    blockFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
    //
    QString turnover;
    cs8ReportDataIterator i(m_turnOverPerDay);
    turnover="<table border=\"1\" cellspacing=\"5\" cellpadding=\"5\">";
    //turnover=+"<colgroup><col width=\"160\"/><col width=\"120\"/></colgroup>";
    turnover+="<tr>";
    turnover+="<th>Verkaufsstelle</th>";
    turnover+="<th>Datum</th>";
    turnover+="<th>Umsatz</th>";
    turnover+="<th>Anteil EB</th>";
    turnover+="<th>Anzahl Artikel</th>";
    turnover+="</tr>";

    int totalQty=0;
    while (i.hasNext())
    {
        i.next();
        QString pos=i.key ();
        cs8ReportData data=i.value();
        cs8SalePerDayIterator j(data);
        while (j.hasNext ())
        {
            j.next ();
            QDate date=j.key ();
            cs8SalePerDay sale=j.value ();
            totalQty+=sale.qtyParts;


            turnover+=trUtf8 ("<tr><td> %1 </td><td> %2 </td><td> %3€ </td><td> %4€ </td><td> %5 </td></tr>")
                    .arg(pos)
                    .arg(date.toString ("dddd, dd.MM.yyyy"))
                    .arg(sale.turnOver,10,'f',2,' ')
                    .arg(sale.turnOver*m_sharePercent/100,10,'f',2,' ')
                    .arg(sale.qtyParts,10,'f',0,' ');
        }
    }
    turnover+=trUtf8 ("<tr><td> Summe </td><td>  </td><td> %3€ </td><td> %4€ </td><td> %5 </td></tr>")
            .arg(m_totalTurnOver,10,'f',2,' ')
            .arg(m_totalTurnOver*m_sharePercent/100,10,'f',2,' ')
            .arg(totalQty,10,'f',0,' ');
    turnover+="</table>";

    m_templateHeader=m_templateHeader
            .arg (QDate::currentDate().toString ())
            .arg(m_totalTurnOver,10,'f',2)
            .arg(turnover)
            .arg(m_sharePercent,3,'f',1)
            .arg(m_shareAbsolute,10,'f',2);

    cursor.insertHtml (m_templateHeader);
    foreach(QString sellerData,m_sellers)
    {
        cursor.insertBlock (blockFormat);
        cursor.insertHtml (sellerData);
    }
    ui->textEdit->setDocument (document);
}

void DialogReportPreview::loadTemplates()
{
    QFile file(":/reportTemplates/ReportTemplateHeader.txt");
    file.open(QFile::ReadOnly);
    QTextStream in(&file);
    in.setCodec ("UTF-8");
    m_templateHeader= in.readAll ();
    file.close ();

    file.setFileName (":/reportTemplates/ReportTemplateSeller.txt");
    file.open(QFile::ReadOnly);
    in.setDevice (&file);
    in.setCodec ("UTF-8");
    m_templateSeller= in.readAll ();
    file.close ();
}

void DialogReportPreview::on_cbSaveAsPdf_clicked()
{
    QPrinter printer;
    printer.setOutputFormat (QPrinter::PdfFormat);
    QString outputFile=QString("%1_%2.pdf")
            .arg("Bericht")
            .arg(QDateTime::currentDateTime ().toString ("yyyyMMdd_hhmmss"));
    qDebug () << "Printing to " << outputFile;
    printer.setOutputFileName (outputFile);
    ui->textEdit->document ()->print (&printer);
    if (QMessageBox::information (this,
                                  trUtf8 ("Bericht"),
                                  trUtf8 ("Der Bericht wurde unter %1 gespeichert.\n"
                                          "Den Bericht im PDF Reader öffnen?").arg(QDir::toNativeSeparators (QDir::currentPath ()+"/"+outputFile)),
                                  QMessageBox::Yes,QMessageBox::No)==QMessageBox::Yes)
    {
        QDesktopServices::openUrl(QDir::currentPath ()+"/"+outputFile);
    }
}
